package com.kzw.oa.dao.system.impl;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.kzw.core.Constants;
import com.kzw.core.dao.impl.BaseDaoImpl;
import com.kzw.core.web.paging.PagingBean;
import com.kzw.oa.dao.system.AppUserDao;
import com.kzw.oa.model.system.AppRole;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.model.system.Department;
import com.kzw.oa.model.system.UserOrg;

@SuppressWarnings("unchecked")
public class AppUserDaoImpl extends BaseDaoImpl<AppUser> implements AppUserDao {

	public AppUserDaoImpl() {
		super(AppUser.class);
	}

	@Override
	public AppUser findByUserName(String username) {
		String hql = "from AppUser au where au.username=?";
		Object[] params = {username};
		List<AppUser> list = findByHql(hql, params);
		AppUser user = null;
		if (list.size() != 0) {
			user = list.get(0);
			
		}		
		return user;
	}

	/**
	 * 根据部门PATH属性查找
	 */
	@Override
	public List findByDepartment(String path, PagingBean pb) {
		List list = new ArrayList();
		String hql = new String();
		if ("0.".equals(path)) {
			hql = "from AppUser vo2 where vo2.delFlag = ?";
			list.add(Constants.FLAG_UNDELETED);
		} else {
			//TODO
			hql="select distinct au from AppUser au where au.department.path like ? and au.delFlag=? ";
//			hql = "select DISTINCT vo2 from Department vo1,AppUser vo2,DepUsers vo3 where 1=1"
//					+ " and vo3.appUser=vo2"
//					+ " and vo3.department=vo1"
//					+ " and vo1.path like ? and vo2.delFlag = ? order by vo3.sn";
			list.add(path + "%");
			list.add(Constants.FLAG_UNDELETED);
		}
		hql += " order by orgSn asc, userSn asc, userId asc";
		return findByHql(hql, list.toArray(), pb);
	}

	@Override
	public List findByDepartment(Department department) {
		String hql = "select vo2 from Department vo1,AppUser vo2 where vo1=vo2.department and vo1.path like ? and vo2.delFlag = ?";
		Object[] params = { department.getPath() + "%",
				Constants.FLAG_UNDELETED };
		return findByHql(hql, params);
	}

	@Override
	public List findByRole(Long roleId) {
		String hql = "select vo from AppUser vo join vo.roles roles where roles.roleId=? and vo.delFlag = ?";
		Object[] objs = { roleId, Constants.FLAG_UNDELETED };
		return findByHql(hql, objs);
	}

	@Override
	public List findByRole(Long roleId, PagingBean pb) {
		String hql = "select vo from AppUser vo join vo.roles roles where roles.roleId=? and vo.delFlag = ?";
		Object[] objs = { roleId, Constants.FLAG_UNDELETED };
		return findByHql(hql, objs, pb);
	}

	@Override
	public List<AppUser> findByDepartment(String path) {
		String hql = "select vo2 from Department vo1,AppUser vo2 where vo1.depId=vo2.depId and vo1.path like ? and vo2.delFlag =?";
		Object[] params = { path + "%", Constants.FLAG_UNDELETED };
		return findByHql(hql, params);
	}

	public List findByRoleId(Long roleId) {
		String hql = "select vo from AppUser vo join vo.roles as roles where roles.roleId=? and vo.delFlag =?";
		return findByHql(hql, new Object[] { roleId, Constants.FLAG_UNDELETED });
	}

	public List findByUserIds(Long... userIds) {
		String hql = "select vo from AppUser vo where vo.delFlag=? ";

		if (userIds == null || userIds.length == 0)
			return null;
		hql += " where vo.userId in (";
		int i = 0;
		for (Long userId : userIds) {
			if (i++ > 0) {
				hql += ",";
			}
			hql += "?";
		}
		hql += " )";

		return findByHql(hql,
				new Object[] { Constants.FLAG_UNDELETED, userIds });
	}

	@Override
	public List<AppUser> findSubAppUser(String path, Set<Long> userIds,
			PagingBean pb) {
		String st = "";
		if (userIds.size() > 0) {
			Iterator<Long> it = userIds.iterator();
			StringBuffer sb = new StringBuffer();
			while (it.hasNext()) {
				sb.append(it.next().toString() + ",");
			}
			sb.deleteCharAt(sb.length() - 1);
			st = sb.toString();
		}

		List list = new ArrayList();
		StringBuffer hql = new StringBuffer();
		if (path != null) {
			hql.append("select vo2 from Department vo1,AppUser vo2 where vo1=vo2.department ");
			hql.append(" and vo1.path like ?");
			list.add(path + "%");
		} else {
			hql.append("from AppUser vo2 where 1=1 ");
		}
		if (st != "") {
			hql.append(" and vo2.userId not in (" + st + ")");
		}
		hql.append(" and vo2.delFlag = ?");
		list.add(Constants.FLAG_UNDELETED);
		return findByHql(hql.toString(), list.toArray(), pb);
	}

	@Override
	public List<AppUser> findSubAppUserByRole(Long roleId, Set<Long> userIds,
			PagingBean pb) {
		String st = "";
		if (userIds.size() > 0) {
			Iterator<Long> it = userIds.iterator();
			StringBuffer sb = new StringBuffer();
			while (it.hasNext()) {
				sb.append(it.next().toString() + ",");
			}
			sb.deleteCharAt(sb.length() - 1);
			st = sb.toString();
		}
		StringBuffer hql = new StringBuffer(
				"select vo from AppUser vo join vo.roles roles where roles.roleId=?");
		List list = new ArrayList();
		list.add(roleId);
		if (st != "") {
			hql.append(" and vo.userId not in (" + st + ")");
		}
		hql.append(" and vo.delFlag =?");
		list.add(Constants.FLAG_UNDELETED);
		return findByHql(hql.toString(), list.toArray(), pb);
	}

	@Override
	public List<AppUser> findByDepId(Long depId) {
		String hql = "from AppUser vo where vo.delFlag=0 and vo.department.depId=?";
		Object[] objs = { depId };
		return findByHql(hql, objs);
	}

	/**
	 * 查找某组角色列表下所有的用户
	 * 
	 * @param roleIds
	 * @return
	 */
	public List<AppUser> findUsersByRoleIds(String roleIds) {
		if (StringUtils.isEmpty(roleIds)) {
			return new ArrayList();
		}
		String hql = "select distinct au from AppUser as au join au.roles as roles where roles.roleId in ("
				+ roleIds + ") and au.delFlag =?";

		return findByHql(hql, new Object[] { Constants.FLAG_UNDELETED });
	}

	

	@Override
	public List<AppUser> findByDepartment(String path, String userIds, PagingBean pb) {
		List<Object> list = new ArrayList<Object>();
		StringBuffer hql = new StringBuffer("");
		if ("0.".equals(path)) {
			hql.append("from AppUser vo2 where vo2.delFlag = ? ");
			list.add(Constants.FLAG_UNDELETED);
		} else {
			hql.append( "select DISTINCT vo2 from Department vo1,AppUser vo2,DepUsers vo3 where 1=1"
					+ " and vo3.appUser=vo2"
					+ " and vo3.department=vo1"
					+ " and vo1.path like ? and vo2.delFlag = ? ");
			list.add(path + "%");
			list.add(Constants.FLAG_UNDELETED);
		}
		//删除userIds中的数据
		if(userIds != null && !userIds.equals("")){
			hql.append("and vo2.userId in (?) ");
			list.add(userIds);
		}
		hql.append("order by vo3.sn "); //排序
		logger.debug("自定义AppUserDaoImpl : " + hql.toString());
		return findByHql(hql.toString(), list.toArray(), pb);
	}
	
	/**
	 * 按角色取得用户列表
	 * @param roleId
	 * @return
	 */
	public List<AppUser> getUsersByRoleId(Long roleId){
		String hql="from AppUser au join au.roles as role where role.roleId=?";
		return (List<AppUser>)findByHql(hql, new Object[]{roleId});
	}
	
	/**
	 * 按部门取得用户列表（FIXME:重新实现）
	 */
	@Override
	public List<AppUser> getDepUsers(String orgPath, PagingBean pb, Map<String, String> map) {
		if(!"0.".equals(orgPath)) {
			//不显示分管领导
			String hql="select distinct uo.appUser from UserOrg uo " +
				"where uo.isPrimary=1 and uo.dept.path like ? and uo.appUser.delFlag=0";
			if(map!=null){
				if(StringUtils.isNotEmpty(map.get("username").toString())){
					hql += "and uo.appUser.username like '%"+map.get("username").toString().trim()+"%' ";
				}
				if(StringUtils.isNotEmpty(map.get("fullname").toString())){
					hql += "and uo.appUser.fullname like '%"+map.get("fullname").toString().trim()+"%' ";
				}
			}
			//排序
			hql += " order by uo.appUser.orgSn asc, uo.appUser.userSn asc";
			if(pb!=null){
				return findByHql(hql, new Object[]{orgPath+"%"}, pb);
			}else{
				return findByHql(hql, new Object[]{orgPath+"%"});
			}
		} else {
			String hql = "from AppUser au where au.delFlag=0";
			if(map!=null){
				if(StringUtils.isNotEmpty(map.get("username").toString())){
					hql += "and au.username like '%"+map.get("username").toString().trim()+"%' ";
				}
				if(StringUtils.isNotEmpty(map.get("fullname").toString())){
					hql += "and au.fullname like '%"+map.get("fullname").toString().trim()+"%' ";
				}
			}
			hql += " order by au.orgSn asc, au.userSn asc";
			if(pb!=null) {
				return findByHql(hql, new Object[]{}, pb);
			}else {
				return findByHql(hql, new Object[]{});
			}
		}
	}
	
	
	/**
	 * 取得组织主要负责人
	 * @param userOrg
	 * @return
	 */
	@Override
	public List<AppUser> getChargeOrgUsers(Set userOrgs) {
		String isChargeUser = "";
		Iterator<UserOrg> it = userOrgs.iterator();
		while(it.hasNext()){
			UserOrg userOrg = it.next();
			if(userOrg.getIsCharge()!=null&&userOrg.getIsCharge()==1){
				isChargeUser += userOrg.getUserid()+",";
			}
		}
		isChargeUser = isChargeUser.length()==0?"0":isChargeUser.substring(0, isChargeUser.length()-1);
		String hql = "from AppUser au where au.userId in ("+isChargeUser+") and au.delFlag=0";
		return findByHql(hql);
	}

	/**
	 * 判断是否为超级管理员
	 * @param userId 用户id
	 * @return 超级管理员true
	 */
	@Override
	public Boolean isSuperMan(Long userId) {
		AppUser appUser = get(userId);
		if (appUser != null && appUser.getRoles() != null && appUser.getRoles().size() > 0) {
			for(AppRole role : appUser.getRoles()){
				if(role != null && (role.getRoleName().equals("超级管理员") || role.getRoleName().equals("管理员") || role.getRights().equals("__ALL"))){
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public List<AppUser> findByDepartment(String path, Integer roleType, PagingBean pb) {
		List list = new ArrayList();
		String hql = new String();
		if ("0.".equals(path)) {
			hql = "from AppUser where delFlag=?";
			list.add(Constants.FLAG_UNDELETED);
			if(roleType != null) {
				hql += " and roleType=?";
				list.add(roleType);
			}
		} else {
			hql = "select distinct au from AppUser au where au.department.path like ? and au.delFlag=? ";
			list.add(path + "%");
			list.add(Constants.FLAG_UNDELETED);
			if(roleType != null) {
				hql += " and roleType=?";
				list.add(roleType);
			}
		}
		hql += " order by orgSn asc, userSn asc, userId asc";
		return findByHql(hql, list.toArray(), pb);
	}
}
